﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace XNET.Core
{
    /// <summary>
    /// 启动外部程序类
    /// </summary>
    public class XApplication
    {
        /// <summary>
        /// 启动外部程序
        /// </summary>
        /// <param name="fileName">程序名</param>
        /// <param name="args">参数</param>
        /// <param name="windowStyle">窗口如何显示</param>
        public static void ExecuteApp(string fileName, string args = "", ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal)
        {
            Process p = new Process();
            p.StartInfo.FileName = fileName;
            if (string.IsNullOrEmpty(args) == false) p.StartInfo.Arguments = args;
            p.StartInfo.WindowStyle = windowStyle;
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();
        }

        /// <summary>
        /// 系统启动时间
        /// </summary>
        /// <returns>返回计算机启动时间</returns>
        public static DateTime SysRunTime()
        {
            return DateTime.Now.AddMilliseconds(0 - System.Environment.TickCount);
        }

        /// <summary>
        /// 开机自动启动程序
        /// </summary>
        /// <param name="exeName">程序名称</param>
        /// <param name="isRun">是否自动启动</param>
        /// <returns></returns>
        public static bool AutoRun(string exeName, bool isRun = true)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (key == null)
            {
                key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
            }
            try
            {
                if (isRun)
                {
                    key.SetValue(exeName, Application.ExecutablePath);
                    key.Close();
                }
                else
                {
                    key.DeleteValue(exeName);
                    key.Close();
                }
            }
            catch { return false; }
            return true;
        }
    }
}
